

import java.io.*;
import java.net.*;
import java.util.*;

/**
* Java class containing functions used to start the server. This
* class is not desiged to be made into an instance. This class also
* contains the static void main method
*
* @file DatoliteServer
* @author Blair Harris
*/
public class DatoliteServer {

    private static ServerSocket this_tcpSocket;
    private static boolean this_run;
    private static LinkedList<DatoliteApplication> this_applications;
    
    private DatoliteServer() {
        
        
    }
	
	/**
	* Initialize the server variables (the socket and applications list)
	*
	* @return 
	*   True if the variables initialized otherwise false
	*/
	public static boolean init() {
		
		this_run = false;
    
    	this_applications = new LinkedList<DatoliteApplication>();
    
        try {
            this_tcpSocket = new ServerSocket(9462);
            return true;
        } catch (IOException ioe) {
            this_tcpSocket = null;
            return false;
        }
        
	}

	/**
	* Start the server listening to incoming request and creating
	* a session to service the request
	*/
    public static void start()  {
    	
    	this_run = true;
    
        try {
        	System.out.print("Starting Datolite Server (port:");
        	System.out.print(9462);
        	System.out.println(")");
        	while (this_run) {
				Socket s = this_tcpSocket.accept();
				DatoliteServer.clientConnected(s);
			}
		} catch (IOException ioe) {
		    ioe.printStackTrace();
		}

   }
   	
   	/**
   	* Stop the server from running and close down network communications
   	*/
    public static void stop() {
        this_run = false;
        try {
        	this_tcpSocket.close();
        } catch (Exception e) {
        
        }
    }
   
   	/**
   	* Load the valid applications found in the servers root directory
   	*
   	* @post
   	*   A list of Datolite applications will be loaded
   	*/
	public static void loadApplications() {
		System.out.println("loading application-------------------------");
		String currentDirectory = "."; 
 
  		String dir;
  		File folder = new File(currentDirectory);
  		File[] directories = folder.listFiles(); 
 
  		for (int i = 0; i < directories.length; i++) {
 
   			if (directories[i].isDirectory()) {
   				dir = directories[i].getName();
   				File appXml = new File(dir + "/app.xml");
   				if (appXml.exists()) {
   					DatoliteServer.addApplication(dir, appXml);
   				}
      		}
  		}
  		System.out.println("finished loading----------------------------");
	}
	
	/**
	* Determines if the server has loaded an application from an ID
	*
	* @param applicationID
	*   The ID of the application to check 
	* @return 
	*   True if the application was loaded otherwise false
	*/
	public static boolean hasApplication(String applicationID) {
		for (DatoliteApplication app : this_applications) {
			if (app.getApplicationID().equals(applicationID))
				return true;
		}
		return false;
	}

	/**
	*
	*/   
	public static DatoliteApplication getApplication(String id) {
		for (DatoliteApplication app : this_applications) {
			if (app.getApplicationID().equals(id))
				return app;
		}
		return null;	
	}
	
	
	private static void clientConnected(Socket s) {
	
		SessionConnector session = new SessionConnector(s);
		Thread thread = new Thread(session);
		thread.start();	

	}
	
	private static void addApplication(String dir, File appXml) {
	   	AppXmlReader xml = new AppXmlReader(appXml);
   		DatoliteApplication app = xml.loadDatoliteApplication(dir);
   					
   					
   		if (app != null) {
   			System.out.println("        loaded '" + dir +"'");
   			
   						
			if (!UipTool.createArchive(app)) {
            	return;
        	}
   			
   			this_applications.add(app);
   			app.createApplicationObject();
   		} 
	}
	
	public static void main(String[] args) {
	
		DatoliteServer.init();
		
		DatoliteServer.loadApplications();
		
		DatoliteServer.start();
		
	}
	
}
